 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=242 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Launch other applications
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Launch other applications</div>

<div class='main-body'>
 
<br>
In Swing applications, the <a href='http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html'>Desktop</a> class gives 
you a simple way to launch common tools found on the great majority of personal computers.
With <tt>Desktop</tt>, you can :
<ul>
 <li>open the default web browser, pointed to a given URI.
 <li>open the default email client, ready to compose an email. 
  This is accomplished by passing a <a href='http://tools.ietf.org/html/rfc2368'>mailTo URI</a> to the <tt>Desktop</tt> class.
  The <tt>mailTo</tt> URI lets you specify the recipients of the email, its subject, and even its content.
  The size of the content is limited, however (which is a bit annoying).
  For example, Microsoft Outlook limits you to 512 characters.
  A second limitation is that file attachments cannot be specified using a <tt>mailto</tt> URI.
</ul> 

<tt>Desktop</tt> also has operations that use the system's <i>file associations</i>, which map file extensions to corresponding default applications.
Such mapping is used to :
<ul>
 <li>open a file for editing or viewing (text file, graphics file, or whatever)
 <li>print a file with an application's print command
</ul> 

<P>The <tt>Desktop</tt> class has a fairly simple API.
Here's an example of its use. 
Note that when you create an email, you often need to pay attention to encoding issues (see below) :
<br>
<PRE>

<span class='keyword'>import</span> java.awt.Desktop;
<span class='keyword'>import</span> java.io.File;
<span class='keyword'>import</span> java.io.IOException;
<span class='keyword'>import</span> java.io.UnsupportedEncodingException;
<span class='keyword'>import</span> java.net.URI;
<span class='keyword'>import</span> java.net.URISyntaxException;
<span class='keyword'>import</span> java.text.CharacterIterator;
<span class='keyword'>import</span> java.text.StringCharacterIterator;
<span class='keyword'>import</span> java.util.regex.Matcher;
<span class='keyword'>import</span> java.util.regex.Pattern;

<span class='comment'>/** Exercise the Desktop class. */</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ExerDesktop {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArgs){
    <span class='keyword'>if</span>(Desktop.isDesktopSupported()){
      ExerDesktop test = <span class='keyword'>new</span> ExerDesktop();
      test.openURLInDefaultBrowser(<span class='literal'>"http://www.date4j.net"</span>);
      <span class='comment'>//hard-coded to a given file :
</span>      test.openFile(<span class='literal'>"C:&#092;&#092;Temp&#092;&#092;blah.txt"</span>);
      test.composeEmail();
    }
    <span class='keyword'>else</span> {
      log(<span class='literal'>"Desktop is not supported by this host."</span>);
    }
  }
  
  <span class='comment'>/** Open a browser. */</span>
  <span class='keyword'>void</span> openURLInDefaultBrowser(String aUrl){
    <span class='keyword'>try</span> {
      URI uri = <span class='keyword'>new</span> URI(aUrl);
      fDesktop.browse(uri);
    }
    <span class='keyword'>catch</span> (URISyntaxException ex) {
      log(<span class='literal'>"URL is malformed. Cannot open browser."</span>);
    }
    <span class='keyword'>catch</span> (IOException ex) {
      log(<span class='literal'>"Cannot open browser."</span>);
    }
  }
  
  <span class='comment'>/**
   Open a file using the system's mapping of file extension to default application. 
  */</span>
  <span class='keyword'>void</span> openFile(String aFileName){
    File file = <span class='keyword'>new</span> File(aFileName);
    <span class='keyword'>try</span> {
      fDesktop.open(file);
    }
    <span class='keyword'>catch</span> (IOException ex) {
      log(<span class='literal'>"File not found: "</span> + aFileName);
    }
  }
  
  <span class='comment'>/** 
   Opens the default email client with prepopulated content, but doesn't send the email.
   You should test your own email clients and character sets.
  */</span>
  <span class='keyword'>void</span> composeEmail(){
    <span class='keyword'>try</span> {
      String url = 
        <span class='literal'>"mailTo:you@xyz.com,me@abc.com"</span> + 
        <span class='literal'>"?subject="</span> + getEmailSubject() + 
        <span class='literal'>"&body="</span> + getEmailBody()
      ;
      URI mailTo = <span class='keyword'>new</span> URI(url);
      <span class='comment'>//log(mailTo);
</span>      fDesktop.mail(mailTo);
    }
    <span class='keyword'>catch</span> (IOException ex) {
      log(<span class='literal'>"Cannot launch mail client"</span>);
    }
    <span class='keyword'>catch</span> (URISyntaxException ex) {
      log(<span class='literal'>"Bad mailTo URI: "</span> + ex.getInput());
    }
  }
  
  <span class='comment'>// PRIVATE
</span>  <span class='keyword'>private</span> Desktop fDesktop = Desktop.getDesktop(); 

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Pattern SIMPLE_CHARS = Pattern.compile(<span class='literal'>"[a-zA-Z0-9]"</span>);
 
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> log(Object aMessage){
    System.out.println(String.valueOf(aMessage));
  }
  
  <span class='keyword'>private</span> String getEmailSubject(){
    <span class='keyword'>return</span> encodeUnusualChars(<span class='literal'>"This is test #1."</span>);
  }
  
  <span class='keyword'>private</span> String getEmailBody(){
    StringBuilder result = <span class='keyword'>new</span> StringBuilder();
    String NL = System.getProperty(<span class='literal'>"line.separator"</span>); 
    result.append(<span class='literal'>"Hello,"</span>);
    result.append(NL);
    result.append(NL);
    <span class='comment'>//exercises a range of common characters :
</span>    result.append(<span class='literal'>"Testing 1 2 3. This is a 'quote', _yes_? ($100.00!) 5*3"</span>);
    <span class='keyword'>return</span> encodeUnusualChars(result.toString());
  }
  
  <span class='comment'>/** 
   This is needed to handle special characters.
   This method hasn't been tested with non-Latin character sets.
   
   Encodes all text except characters matching [a-zA-Z0-9]. 
   All other characters are hex-encoded. The encoding is '%' plus the hex 
   representation of the character in UTF-8. 
   
   &lt;P&gt;See also :
   http://tools.ietf.org/html/rfc2368 - mailto
   http://tools.ietf.org/html/rfc1738 - URLs
  */</span>
  <span class='keyword'>private</span> String encodeUnusualChars(String aText){
    StringBuilder result = <span class='keyword'>new</span> StringBuilder();
    CharacterIterator iter = <span class='keyword'>new</span> StringCharacterIterator(aText);
    <span class='keyword'>for</span>(<span class='keyword'>char</span> c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
      <span class='keyword'>char</span>[] chars = {c};
      String character = <span class='keyword'>new</span> String(chars);
      <span class='keyword'>if</span>(isSimpleCharacter(character)){
        result.append(c);
      }
      <span class='keyword'>else</span> {
        hexEncode(character, <span class='literal'>"UTF-8"</span>, result);
      }
    }
    <span class='keyword'>return</span> result.toString();
  }
  
  <span class='keyword'>private</span> <span class='keyword'>boolean</span> isSimpleCharacter(String aCharacter){
    Matcher matcher = SIMPLE_CHARS.matcher(aCharacter);
    <span class='keyword'>return</span> matcher.matches();
  }
  
  <span class='comment'>/**
   For the given character and encoding, appends one or more hex-encoded characters.
   For double-byte characters, two hex-encoded items will be appended.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> hexEncode(String aCharacter, String aEncoding, StringBuilder aOut) {
    <span class='keyword'>try</span>  {
      String HEX_DIGITS = <span class='literal'>"0123456789ABCDEF"</span>; 
      <span class='keyword'>byte</span>[] bytes = aCharacter.getBytes(aEncoding);
      <span class='keyword'>for</span> (<span class='keyword'>int</span> idx = <span class='literal'>0</span>; idx &lt; bytes.length; idx++) {
        aOut.append(<span class='literal'>'%'</span>);
        aOut.append(HEX_DIGITS.charAt((bytes[idx] &amp; <span class='literal'>0xf0</span>) &gt;&gt; <span class='literal'>4</span>));
        aOut.append(HEX_DIGITS.charAt(bytes[idx] &amp; <span class='literal'>0xf</span>));
      }
    }
    <span class='keyword'>catch</span> (UnsupportedEncodingException ex) {
      log(ex.getStackTrace());
    }
  }
} 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction895b-2.html?Id=144'>Send an email</a> <br>
 
  
  <a href='TopicActionc3f2-2.html?Id=179'>Send trouble-ticket emails</a> <br>
 
  
  <a href='TopicActiond957-2.html?Id=180'>Validate email addresses</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='242'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=242 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
